﻿using Sidvall.WorkItemManager.Data;
using Sidvall.WorkItemManager.Net.Services.V1;
using System.Threading.Tasks;

namespace Sidvall.WorkItemManager.Workflow.Conditions
{
	public class ScheduleConditionProvider : ConditionProviderBase
	{
		#region Public Members

		public override Task<bool> CanExecuteAsync(IWorkItem item)
		{
			bool isExecutionTime;

			if (item == null)
				throw new System.ArgumentNullException("item");

			DeserializeContext();
			isExecutionTime = this.Schedule.IsExecutionTime(System.DateTime.Now, item.LastExecutionEndTime);

			return Task.FromResult(isExecutionTime);
		}

		public override Task<string> GetDescriptionAsync(IWorkItem item)
		{
			System.DateTime? time;
			string description;

			if (item == null)
				throw new System.ArgumentNullException("item");

			DeserializeContext();
			description = Sidvall.WorkItemManager.SystemContextConfig.Current.EntityFacade.ScheduleManager.GetScheduleDescription(this.Schedule);
			if (item.ExecutionContext != null)
			{
				time = this.Schedule.GetNextExecutionTime(System.DateTime.Now, item.LastExecutionEndTime);
				if (time != null)
					description += System.Environment.NewLine + "Scheduled for " + time.ToString();
				else
					description += System.Environment.NewLine + "Not scheduled to run";
			}
			return Task.FromResult(description);
		}

		#endregion
		#region Private Members

		private Schedule Schedule { get; set; }

		private void DeserializeContext()
		{
			if (!string.IsNullOrWhiteSpace(this.Context))
				this.Schedule = Sidvall.Serialization.SerializerManager.Current.Deserialize<Schedule>(this.Context);
			else
				this.Schedule = null;
			if (this.Schedule == null)
				throw new System.ArgumentException("Invalid schedule settings.");
		}

		#endregion
	}
}
